package com.bsoft.gol.hbs.service.impl;
import com.bsoft.gol.hbs.dao.OnlineConsultConfigDAO;
import com.bsoft.gol.hbs.dao.OnlineConsultLanguageDAO;
import com.bsoft.gol.hbs.dao.OnlineConsultPriceDAO;
import com.bsoft.gol.hbs.utils.Constants;
import ctd.controller.exception.ControllerException;
import ctd.dictionary.Dictionary;
import ctd.dictionary.DictionaryItem;
import ctd.dictionary.controller.DictionaryController;
import ctd.spring.boot.annotation.SsdevService;
import ctd.util.BeanUtils;
import ctd.util.annotation.RpcService;
import hcn.service.consult.OnlineConfigService;
import hcn.util.CommonUtils;
import hcn.util.RpcUserToken;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import pcn.bean.consultation.DoctorSortQo;
import pcn.bean.consultation.OnlineConsultLanguageQo;
import pcn.bean.consultation.SequenseVo;
import pcn.consultation.*;
import pcn.enums.DoctorTitleEnum;
import pcn.enums.NoNeedInitConsultType;
import pcn.vo.consultation.GetDoctorConfigPriceVo;
import service.rpc.DoctorInfoServiceIntf;
import service.rpc.DoctorRecommendConfigRpcService;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 常用语接口
 *
 * @author niule
 */
@SsdevService("onlineConfigService")
public class OnlineConfigServiceImpl implements OnlineConfigService {

    @Autowired
    private OnlineConsultLanguageDAO onlineConsultLanguageDAO;
    @Autowired
    private OnlineConsultConfigDAO onlineConsultConfigDAO;
    @Autowired
    private DoctorRecommendConfigRpcService doctorRecommendConfigRpcService;
    @Autowired
    private OnlineConsultPriceDAO onlineConsultPriceDAO;
    @Autowired
    private DoctorInfoServiceIntf doctorInfoService;

    /**
     * 常用语获取
     *
     * @param objectId   对象id
     * @param objectType 011租户级 021机构级
     * @return
     */
    @RpcService
    @Override
    public List<OnlineConsultLanguage> queryOnlineConsultLanguage(String objectId, String objectType) throws ControllerException {
        if (CommonUtils.isEmpty(objectType)) {
            throw new ControllerException("objectType不能为空");
        }
        if (CommonUtils.isEmpty(objectId)) {
            throw new ControllerException("objectId不能为空");
        }
        return onlineConsultLanguageDAO.findOnlineConsultLanguage(objectId, objectType);
    }


    /**
     * 保存常用语
     *
     * @param onlineConsultLanguageQo
     * @return
     */
    @RpcService
    @Override
    public int saveOnlineConsultLanguage(OnlineConsultLanguageQo onlineConsultLanguageQo) throws ControllerException {
        try {
            OnlineConsultLanguage onlineConsultLanguage=new OnlineConsultLanguage();
            BeanUtils.copy(onlineConsultLanguageQo,onlineConsultLanguage);
            if (CommonUtils.isEmpty(onlineConsultLanguage.getContext())) {
                throw new ControllerException("常用语记录内容不能为空");
            }
            if (CommonUtils.isEmpty(onlineConsultLanguage.getObjectType())) {
                throw new ControllerException("objectType不能为空");
            }
            if (CommonUtils.isEmpty(onlineConsultLanguage.getObjectId())) {
                throw new ControllerException("objectId不能为空");
            }

            onlineConsultLanguage.setStatus((byte) 1);
            OnlineConsultLanguage con = onlineConsultLanguageDAO.save(onlineConsultLanguage);
            return con.getId();
        } catch (ControllerException e) {
            throw new ControllerException(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            throw new ControllerException("更新常用语失败");
        }

    }


    /**
     * 编辑常用语
     *
     * @param onlineConsultLanguage
     * @return
     */
    @RpcService
    @Override
    public int updateOnlineConsultLanguage(OnlineConsultLanguage onlineConsultLanguage) throws ControllerException {
        try {
            if (CommonUtils.isEmpty(onlineConsultLanguage.getId()) || onlineConsultLanguage.getId() == 0) {
                throw new ControllerException("常用语记录id不能为空");
            }
            OnlineConsultLanguage consultLanguage = onlineConsultLanguageDAO.get(onlineConsultLanguage.getId());
            if (null == consultLanguage) {
                throw new ControllerException("该记录不存在");
            }
            consultLanguage.setContext(onlineConsultLanguage.getContext());
            if (null != onlineConsultLanguage.getStatus()) {
                consultLanguage.setStatus(consultLanguage.getStatus());
            }
            onlineConsultLanguageDAO.update(consultLanguage);
            return consultLanguage.getId();
        } catch (ControllerException e) {
            throw new ControllerException(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            throw new ControllerException("更新常用语失败");
        }
    }

    /**
     * 删除常用语
     *
     * @param id
     * @return
     */
    @RpcService
    @Override
    public void deleteOnlineConsultLanguage(Integer id) throws ControllerException {
        try {
            if (CommonUtils.isEmpty(id) || id.intValue() == 0) {
                throw new ControllerException("常用语记录id不能为空");
            }
            OnlineConsultLanguage consultLanguage = onlineConsultLanguageDAO.get(id);
            if (null == consultLanguage) {
                throw new ControllerException("该记录不存在");
            }
            consultLanguage.setStatus((byte) 0);
            onlineConsultLanguageDAO.update(consultLanguage);
        } catch (ControllerException e) {
            throw new ControllerException(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            throw new ControllerException("更新常用语失败");
        }
    }

    /**
     * @Describe: 获取默认配置
     * @Param: [objectType, objectId]
     * @Return: pcn.consultation.OnlineConsultConfig
     * @Author: zhengcb10708
     * @Date: 2021/5/28 13:23
     */
    @RpcService
    @Override
    public OnlineConsultConfig getOnlineConsultConfig(String objectId, String objectType) throws ControllerException {
        return onlineConsultConfigDAO.getOnlineConsultConfig(objectId,objectType);
    }

    /**
     * 医生排序
     *
     * @param doctorSortQo
     * @return
     */
    @RpcService
    @Override
    public Map<String, Object> quaryDoctorRecommendList(DoctorSortQo doctorSortQo) throws ControllerException {
        try {
            Map<String, Object> map = new HashMap<>();
            OnlineConsultConfig onlineConsultConfig = onlineConsultConfigDAO.getOnlineConsultConfig(doctorSortQo.getObjectId(), doctorSortQo.getObjectType());
            if (CommonUtils.isEmpty(doctorSortQo.getSort())) {
                doctorSortQo.setSort(String.valueOf(onlineConsultConfig.getSortType()));
            }

            List<SequenseVo> sequenseVos = doctorRecommendConfigRpcService.quaryDoctorRecommendList(doctorSortQo);
            Long total = doctorRecommendConfigRpcService.getDoctorRecommendCount(doctorSortQo);
//            int first = doctorSortQo.getPageNo() > 0 ? (doctorSortQo.getPageNo() - 1) * doctorSortQo.getPageSize() : 0;
//            int end =  doctorSortQo.getPageNo() > 0 ? doctorSortQo.getPageNo() * doctorSortQo.getPageSize() : doctorSortQo.getPageSize();
//            List<SequenseVo> list = null;
//            if(CommonUtils.isNotEmpty(sequenseVos)){
//                if((doctorSortQo.getPageNo()-1) * doctorSortQo.getPageSize()>sequenseVos.size()){
//
//                }else if(doctorSortQo.getPageNo() * doctorSortQo.getPageSize()>sequenseVos.size()){
//                    list = sequenseVos.subList(first,sequenseVos.size());
//                }else {
//                    list = sequenseVos.subList(first,end);
//                }
//
//                map.put("list",list);
//            }
            map.put("list", sequenseVos);
            map.put("total", total);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ControllerException("获取医生排序列表失败");
        }
    }

    /**
     * 移动排序位置
     *
     * @param id
     * @param positionType
     */
    @RpcService
    @Override
    public void positionTransform(int id, String positionType) throws ControllerException {
        try {
            DoctorRecommendConfig doctorRecommendConfig = doctorRecommendConfigRpcService.get(id);
            int numberflag = doctorRecommendConfig.getSerialNumber();
            if ("up".equals(positionType)) {
                DoctorRecommendConfig before_doctorRecommendConfig = doctorRecommendConfigRpcService.getDoctorRecommendConfigByNumber(doctorRecommendConfig.getObjectId(), doctorRecommendConfig.getObjectType(), numberflag, false);
                if (CommonUtils.isEmpty(before_doctorRecommendConfig)) {
                    return;
                }
                int changeIndex = before_doctorRecommendConfig.getSerialNumber();
                before_doctorRecommendConfig.setSerialNumber(doctorRecommendConfig.getSerialNumber());
                doctorRecommendConfigRpcService.update(before_doctorRecommendConfig);
                doctorRecommendConfig.setSerialNumber(changeIndex);
                doctorRecommendConfigRpcService.update(doctorRecommendConfig);
            }
            if ("down".equals(positionType)) {
                DoctorRecommendConfig next_doctorRecommendConfig = doctorRecommendConfigRpcService.getDoctorRecommendConfigByNumber(doctorRecommendConfig.getObjectId(), doctorRecommendConfig.getObjectType(), numberflag, true);
                if (CommonUtils.isEmpty(next_doctorRecommendConfig)) {
                    return;
                }
                int changeIndex = next_doctorRecommendConfig.getSerialNumber();
                next_doctorRecommendConfig.setSerialNumber(doctorRecommendConfig.getSerialNumber());
                doctorRecommendConfigRpcService.update(next_doctorRecommendConfig);
                doctorRecommendConfig.setSerialNumber(changeIndex);
                doctorRecommendConfigRpcService.update(doctorRecommendConfig);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ControllerException("修改医生排序失败");
        }
    }

    /**
     * 推荐和取消推荐
     *
     * @param recommendConfig
     */
    @RpcService
    @Override
    public void updateRecommondFlag(DoctorRecommendConfig recommendConfig) throws ControllerException {
        if (recommendConfig.getId() == 0) {//则表示需要推荐
            DoctorRecommendConfig new_recommendConfig = new DoctorRecommendConfig();
            int beginIndex = 0;
            List<DoctorRecommendConfig> recommendConfigs = doctorRecommendConfigRpcService.queryDoctorRecommendConfigByObjectIdANDObjectType(recommendConfig.getObjectId(), recommendConfig.getObjectType());
            if (CommonUtils.isNotEmpty(recommendConfigs) && null != recommendConfigs.get(0).getSerialNumber()) {
                beginIndex = recommendConfigs.get(0).getSerialNumber();
            }
            new_recommendConfig.setSerialNumber(beginIndex + 1);
            new_recommendConfig.setObjectType(recommendConfig.getObjectType());
            new_recommendConfig.setObjectId(recommendConfig.getObjectId());
            new_recommendConfig.setDoctorId(recommendConfig.getDoctorId());
            new_recommendConfig.setRecommendFlag((byte) 1);
            doctorRecommendConfigRpcService.save(new_recommendConfig);
        } else {//取消推荐，直接删除
            doctorRecommendConfigRpcService.remove(recommendConfig.getId());
        }
    }

    /**
     * 获取医生初始化价格列表
     *
     * @param objectId
     * @param objectType
     * @return
     */
    @RpcService
    @Override
    public GetDoctorConfigPriceVo getDoctorConfigPrice(String objectType, String objectId) {
        GetDoctorConfigPriceVo getDoctorConfigPriceVo = new GetDoctorConfigPriceVo();
        OnlineConsultConfig onlineConsultConfig = onlineConsultConfigDAO.getOnlineConsultConfig(objectId, objectType);

        if(null == onlineConsultConfig){
            //获取租户的
            onlineConsultConfig = onlineConsultConfigDAO.getOnlineConsultConfig(RpcUserToken.getTenantId(), "2");
        }

        if(null == onlineConsultConfig){
            onlineConsultConfig = new OnlineConsultConfig();
            onlineConsultConfig.setId(0);
            onlineConsultConfig.setTenantId(RpcUserToken.getTenantId());
            onlineConsultConfig.setOrgId(objectId);
            onlineConsultConfig.setObjectType(objectType);
            onlineConsultConfig.setObjectId(objectId);
            onlineConsultConfig.setOpenServiceFlag((byte)0);
            onlineConsultConfig.setChangePriceFlag((byte)0);
            onlineConsultConfig.setStatus((byte)1);
            onlineConsultConfig.setSortType((byte)0);
        }


        getDoctorConfigPriceVo.setOnlineConsultConfig(onlineConsultConfig);
        try {
            if (CommonUtils.isNotEmpty(onlineConsultConfig)) {
                Dictionary dictionary = DictionaryController.instance().get("HCN_consultType");
                List<DictionaryItem> dicItems = dictionary.getSlice(null, 0, null);

                List<GetDoctorConfigPriceVo.ConsultTypeConsultPrice> consultTypeConsultPrices = new ArrayList<>();
                GetDoctorConfigPriceVo.ConsultTypeConsultPrice consultTypeConsultPrice = null;


                for (DictionaryItem dicItem : dicItems) {
                    // 过滤掉无需初始化的问诊类型
                    if (!Arrays.stream(NoNeedInitConsultType.values()).map(NoNeedInitConsultType::getKey)
                            .collect(Collectors.toList()).contains(dicItem.getKey())) {
                    consultTypeConsultPrice = new GetDoctorConfigPriceVo.ConsultTypeConsultPrice();
                    consultTypeConsultPrice.setConsultType(dicItem.getKey());
                    consultTypeConsultPrice.setConsultTypeName(dicItem.getText());

                    List<String> doctorTitleList = Arrays.asList(DoctorTitleEnum.ZRYS.getTitle(), DoctorTitleEnum.FZRYS.getTitle(), DoctorTitleEnum.ZZYS.getTitle(), DoctorTitleEnum.YS.getTitle());

                    //查询非普通号的医生
                    List<OnlineConsultPrice> onlineConsultPriceList = onlineConsultPriceDAO.queryByDoctorLevelList(onlineConsultConfig.getId(), dicItem.getKey(), doctorTitleList);
                    if (null == onlineConsultConfig) {
                        onlineConsultPriceList = new ArrayList<>();
                    }

                    List<String> collect = onlineConsultPriceList.stream().map(OnlineConsultPrice::getDoctorLevel).collect(Collectors.toList());
                    if (null == collect) {
                        collect = new ArrayList<>();
                    }

                        for (String doctorTitle : doctorTitleList) {
                            //若是返回里面没有这个医生职称，那么就新增
                            if (!collect.contains(doctorTitle)) {
                                OnlineConsultPrice onlineConsultPrice = new OnlineConsultPrice();
                                onlineConsultPrice.setId(0);
                                onlineConsultPrice.setConfigId(onlineConsultConfig.getId());
                                onlineConsultPrice.setConsultType(dicItem.getKey());
                                onlineConsultPrice.setDoctorLevel(doctorTitle);
                                onlineConsultPrice.setPrice(BigDecimal.ZERO);
                                onlineConsultPrice.setDiscountPrice(BigDecimal.ZERO);
                                onlineConsultPrice.setStatus((byte) 1);
                                onlineConsultPriceList.add(onlineConsultPrice);
                            }
                        }

                    //添加排序 医生职称代码升序
                    Collections.sort(onlineConsultPriceList, new Comparator<OnlineConsultPrice>() {
                        public int compare(OnlineConsultPrice o1, OnlineConsultPrice o2) {
                            Integer doctorLevel1 = Integer.valueOf(o1.getDoctorLevel());
                            Integer doctorLevel2 = Integer.valueOf(o2.getDoctorLevel());
                            return doctorLevel1.compareTo(doctorLevel2);
                        }
                    });

                    OnlineConsultPrice deptOnlineConsultPrice = onlineConsultPriceDAO.getOnlineConsultPriceByLevel(onlineConsultConfig.getId(), dicItem.getKey());
                    if (null == deptOnlineConsultPrice) {
                        deptOnlineConsultPrice = new OnlineConsultPrice();
                        deptOnlineConsultPrice.setId(0);
                        deptOnlineConsultPrice.setConfigId(onlineConsultConfig.getId());
                        deptOnlineConsultPrice.setConsultType(dicItem.getKey());
                        deptOnlineConsultPrice.setDoctorLevel(Constants.ZERO.toString());
                        deptOnlineConsultPrice.setPrice(BigDecimal.ZERO);
                        deptOnlineConsultPrice.setDiscountPrice(BigDecimal.ZERO);
                        deptOnlineConsultPrice.setStatus((byte) 1);
                    }
                    onlineConsultPriceList.add(deptOnlineConsultPrice);

                    consultTypeConsultPrice.setOnlineConsultPriceList(onlineConsultPriceList);
                    consultTypeConsultPrices.add(consultTypeConsultPrice);
                }
            }

                //添加排序 医生职称代码升序
                Collections.sort(consultTypeConsultPrices, new Comparator<GetDoctorConfigPriceVo.ConsultTypeConsultPrice>() {
                    public int compare(GetDoctorConfigPriceVo.ConsultTypeConsultPrice o1, GetDoctorConfigPriceVo.ConsultTypeConsultPrice o2) {
                        return o1.getConsultType().compareTo(o2.getConsultType());
                    }
                });

                getDoctorConfigPriceVo.setConsultTypeConsultPriceList(consultTypeConsultPrices);
            }
        } catch (ControllerException e) {
            e.printStackTrace();
        }

        return getDoctorConfigPriceVo;
    }

    /**
     * 通过某个类型去查询
     *
     * @param consultType
     * @return
     */
    @RpcService
    @Override
    public List<Map<String, Object>> queryOnlineConsultPriceByConsultType(int configId, String consultType) {
        List<Map<String, Object>> mapList = new ArrayList<>();
        List<OnlineConsultPrice> onlineConsultPriceList = onlineConsultPriceDAO.queryOnlineConsultPriceByConsultType(configId, consultType);
        for (OnlineConsultPrice onlineConsultPrice : onlineConsultPriceList) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", onlineConsultPrice.getId());
            map.put("configId", onlineConsultPrice.getConfigId());
            map.put("doctorLevel", onlineConsultPrice.getDoctorLevel());
            map.put("price", onlineConsultPrice.getPrice());
            map.put("discountPrice", onlineConsultPrice.getDiscountPrice());
            mapList.add(map);
        }
        return mapList;
    }


    /**
     * 保存或者修改初始化价格
     *
     * @param onlineConsultConfig
     * @param onlineConsultPriceList
     */
    @RpcService
    @Override
    public void updateOnlineConsultPrice(OnlineConsultConfig onlineConsultConfig, List<OnlineConsultPrice> onlineConsultPriceList) {
        OnlineConsultConfig new_onlineConsultConfig = null;
        if(null == onlineConsultConfig.getId() || 0 == onlineConsultConfig.getId()){
            OnlineConsultConfig exist = onlineConsultConfigDAO.getOnlineConsultConfig(onlineConsultConfig.getObjectId(), onlineConsultConfig.getObjectType());
            if(exist!=null) {
                onlineConsultConfig.setId(exist.getId());
            }
        }

        if (0 == onlineConsultConfig.getId()) {
            onlineConsultConfig = onlineConsultConfigDAO.save(onlineConsultConfig);
        }else {
            onlineConsultConfig = onlineConsultConfigDAO.update(onlineConsultConfig);
        }

        if(CommonUtils.isNotEmpty(onlineConsultPriceList)){
            for (OnlineConsultPrice onlineConsultPrice : onlineConsultPriceList) {
                onlineConsultPrice.setConfigId(onlineConsultConfig.getId());

                OnlineConsultPrice existOnlineConsultPrice = onlineConsultPriceDAO.get(onlineConsultPrice.getId());
                if (null != existOnlineConsultPrice) {
                    onlineConsultPrice.setId(existOnlineConsultPrice.getId());
                    onlineConsultPriceDAO.update(onlineConsultPrice);
                } else {
                    onlineConsultPriceDAO.save(onlineConsultPrice);
                }

            }
        }
    }

   /**
     * 保存医生排序规则
     *
     * @param objectId
     * @param objectType sortType
     */
    @RpcService
    @Override
    public void updateOnlineConsultConfig(String objectId, String objectType, byte sortType) {
        OnlineConsultConfig onlineConsultConfig = onlineConsultConfigDAO.getOnlineConsultConfig(objectId, objectType);
        onlineConsultConfig.setSortType(sortType);
        onlineConsultConfigDAO.update(onlineConsultConfig);
    }

    /**
     * 根据医生id和科室id查询互联网诊疗配置
     *
     * @param deptId   科室id
     * @param doctorId 医生id
     * @return 互联网诊疗配置
     */
    @RpcService
    @Override
    public List<ConsultDoctorConfig> getDoctorConsultConfigByDoctorIdAndDeptId(String deptId, String doctorId) throws ControllerException {
        if (StringUtils.isEmpty(deptId) || StringUtils.isEmpty(doctorId)) {
            return null;
        }
        return doctorInfoService.getDoctorOnlineConfigByDoctorIdANDdeptId(deptId, doctorId);
    }
    /**
     * @Describe: 按条件查询在线问诊默认配置
     * @Param: [orgId, consulttype, doctorlevel]
     * @Return: java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     * @Author: zhengcb10708
     * @Date: 2021/7/14 16:17
     */
    @RpcService
    @Override
    public List<Map<String,Object>> queryOnlineConsultConfigByParams(String orgId,String consulttype,String doctorlevel) throws ControllerException {
        return onlineConsultPriceDAO.queryOnlineConsultConfigByParams(orgId,consulttype,doctorlevel);
    }


    /**
     * @Author:FangZhiYi
     * @Description 查询科室普通号问诊价格
     * @Params  [deptId]
     * @Return  java.util.List<pcn.consultation.OnlineConsultPrice>
     * @Data Created in 2021/11/16 11:22
     * @Moddified By:
     */
    @RpcService
    @Override
    public List<OnlineConsultPrice> queryDeptConsultPrice(String deptId) throws ControllerException {
        return onlineConsultPriceDAO.queryDeptConsultPrice();
    }

}
